﻿using System.ComponentModel;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Devonline.Identity.Admin.Controllers;

/// <summary>
/// 组织部门管理
/// </summary>    
[ApiController]
[Route("api/[controller]")]
[Description("组织单位管理")]
[Authorize(Roles = GROUP_MAINTAINERS)]
[AccessAuthorize(Code = "AS0XGroup", Name = "组织单位管理", ResourceType = ResourceType.Service, Roles = GROUP_MAINTAINERS)]
public class GroupsController(
    ILogger<GroupsController> logger,
    IDataWithAttachmentService<Group> dataService,
    GroupStore groupStore) :
    IdentityDataModelServiceController<Group, GroupViewModel>(logger, dataService)
{
    private readonly GroupStore _groupStore = groupStore;

    /// <summary>
    /// 获取组织机构树形结构数据
    /// </summary>
    /// <returns></returns>
    [HttpGet("GetGroupTreeData")]
    [DisplayName("获取组织机构树形结构数据")]
    [AccessAuthorize(Code = "AS0XGroupIGetGroupTreeData")]
    public async Task<IActionResult> GetGroupTreeDataAsync()
    {
        var all = await _dataService.GetQueryable(x => x.State == DataState.Available).Include(x => x.Parent).OrderBy(x => x.Name).ToListAsync();
        var roots = new List<GroupWithChildrenViewModel>();
        if (all is not null && all.Count > 0)
        {
            var allGroups = all.ConvertAll<Group, GroupWithChildrenViewModel>();
            if (allGroups is not null && allGroups.Any())
            {
                roots = allGroups.Where(x => x.ParentId == null).ToList();
                foreach (var group in roots)
                {
                    GetChildrenGroups(group, allGroups);
                }
            }
        }

        return Ok(roots);
    }

    /// <summary>
    /// 获取子级组织机构
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("GetChildrenGroups/{id}")]
    [DisplayName("获取子级组织机构")]
    [AccessAuthorize(Code = "AS0XGroupIGetChildrenGroups")]
    public async Task<IActionResult> GetChildrenGroupsAsync(string id) => Ok(await _groupStore.GetChildrenGroupsAsync(id, Request.GetRequestOption<bool>("recursion")));

    /// <summary>
    /// 递归获取所有组织机构(包含上下级关系)
    /// </summary>
    /// <param name="group">当前组织机构</param>
    /// <param name="groups">所有组织机构</param>
    private static void GetChildrenGroups(GroupWithChildrenViewModel group, IEnumerable<GroupWithChildrenViewModel> groups)
    {
        var children = groups.Where(x => x.ParentId == group.Id).OrderBy(x => x.Name).ToList();
        if (children is not null && children.Count != 0)
        {
            group.Children = children;
            foreach (var child in children)
            {
                GetChildrenGroups(child, groups);
            }
        }
    }
}